<!DOCTYPE html>
<html>
<head>
<script src="annotations.js"></script>
<script>
const supportsFLV  = !!document.createElement("video").canPlayType("video/x-flv");
const supportsAVI  = !!document.createElement("video").canPlayType("video/avi");
const supportsWMV  = !!document.createElement("video").canPlayType("video/x-ms-wmv");
const supportsWebM = !!document.createElement("video").canPlayType("video/webm") && false;
const FLV = "FLV";
const MP4 = "MP4";
const WEBM = "WEBM";

function downloadURL(url){
    safari.application.activeBrowserWindow.activeTab.page.dispatchMessage("downloadURL",url);
}

function viewInQuickTimePlayer(mediaURL){
    safari.application.activeBrowserWindow.activeTab.page.dispatchMessage("viewQT",mediaURL);
};

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

String.prototype.parseInt = function(){
	return parseInt(this);
};

String.prototype.contains = function(str){
	return this.indexOf(str) != -1
};

/**
 * Usage  var you = 'hello you guys'.between('hello ',' guys');
 * you = 'you';
 */
String.prototype.between = function(prefix, suffix) {
	s = this;
	var i = s.indexOf(prefix);
	if (i >= 0) {
		s = s.substring(i + prefix.length);
 	}
	if (suffix) {
		i = s.indexOf(suffix);
		if (i >= 0) {
	  		s = s.substring(0, i);
		}
	}
	return s.toString();
};

String.prototype.trim = function() {
	str = this.replace(/^\s+/, '');
	for (var i = str.length - 1; i >= 0; i--) {
		if (/\S/.test(str.charAt(i))) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return str;
};

function getQueryString(queryString) {
	var assoc = {};
	var keyValues = queryString.split('&');
	for (var i = 0; i < keyValues.length; i++) {
		var split = keyValues[i].split('=');
		var key = split.shift();
		var value = split.join("=");
		if(!value){
			value = true;
		}else if(value.toLowerCase() == "true"){
			value = true;
		}else if(value.toLowerCase() == "false"){
			value = false;
		}
		assoc[key] = unescape(value).replace(/\+/g," ");
	}
	return assoc;
}

Element.prototype.getParamByName = function(name){
	params = this.params;
	for(i = 0; i < params.length; i++){
		if(params[i].getAttribute("name").toLowerCase == name.toLowerCase){
			return params[i];
		}
	}
	return false;
}

// NOTE: The following bit of code was taken directly from Javascript Blacklist. Thanks to the guys over there. I suck at regexes, and their code works, so I'm "borrowing" it. Code reuse is the sincerest form of flattery, right?
// Escapes special characters with backslashes.
function escape(text) {
	if (!arguments.callee.escapeRE) {
		var specials = [ ".", "*", "+", "?", "|", "(", ")", "[", "]", "{", "}", "\\" ];
		arguments.callee.escapeRE = new RegExp( "(\\" + specials.join("|\\") + ")", "g" );
	}
	return text.replace(arguments.callee.escapeRE, "\\$1");
}

// Rebuild the blacklist from the settings. This is triggered automatically the first
// time the script runs, and via a listener when the user modifies the settings.
function rebuildHostWhitelist() {
	var str = safari.extension.settings.getItem("host_whitelist");
	var sites = str.split(/ *, */);
	var re;
	if (sites.length <= 0) {
		re = new RegExp("$^"); // a RegExp that never matches
	} else {
		for (var i=0; i<sites.length; i++) {
			sites[i] = escape(sites[i]);
		}
		re = new RegExp("[./](" + sites.join("|") + ")/", "i");
	}
	
	document.hostWhitelist = re;
}
function rebuildSiteWhitelist() {
	var str = safari.extension.settings.getItem("site_whitelist");
	var sites = str.split(/ *, */);
	var re;
	if (sites.length <= 0) {
		re = new RegExp("$^"); // a RegExp that never matches
	} else {
		for (var i=0; i<sites.length; i++) {
			sites[i] = escape(sites[i]);
		}
		re = new RegExp("[./](" + sites.join("|") + ")/", "i");
	}
	
	document.siteWhitelist = re;
}
function rebuildTypeWhitelist() {
	var str = safari.extension.settings.getItem("type_whitelist");
	var sites = str.split(/ *, */);
	var re;
	if (sites.length <= 0) {
		re = new RegExp("$^"); // a RegExp that never matches
	} else {
		for (var i=0; i<sites.length; i++) {
			sites[i] = escape(sites[i]);
		}
		re = new RegExp("[./](" + sites.join("|") + ")/", "i");
	}
	
	document.typeWhitelist = re;
}

// Cache the RegExp objects in this document for speed.
function getTypeWhitelist() {
	if (!document.typeWhitelist) {
		rebuildTypeWhitelist();
	}
	return document.typeWhitelist;
}
function getHostWhitelist() {
	if (!document.hostWhitelist) {
		rebuildHostWhitelist();
	}
	return document.hostWhitelist;
}
function getSiteWhitelist() {
	if (!document.siteWhitelist) {
		rebuildSiteWhitelist();
	}
	return document.siteWhitelist;
}

// Handle configuration change messages from Safari.
function changeListener(event) {
	if (event.key === "site_whitelist") {
		rebuildSiteWhitelist();
	}else if(event.key === "host_whitelist"){
		rebuildHostWhitelist();
	}
}

safari.extension.settings.addEventListener("change", changeListener, false);

function testWhitelists(url, windowURL, type) {
	if (windowURL.search(getSiteWhitelist()) == -1) {
		if(url.search(getHostWhitelist()) == -1){
			if(type.search(getTypeWhitelist()) == -1){
				return false;
			}
		}
	}
	return true;
}

// END STOLEN CODE FROM JS BLACKLIST

function sendBuildMessage(video){
	safari.application.activeBrowserWindow.activeTab.page.dispatchMessage("buildYTPlayer",video);
}

function allowContentToLoad(url, nodeName, width, height, elid, className, windowURL, type)
{
	if (safari.extension.settings.enablePluginBlocking === false){
		return true;
	}
	if (nodeName === "OBJECT" || nodeName === "EMBED" || nodeName === "APPLET"){
		if (((width <= 8) || (height <= 8)) && safari.extension.settings.autoLoadInvisible === true){
			return true;
		}else if(safari.extension.settings.sIFR == "load" && className.indexOf("sIFR") != (-1)){
			return true;
		}else{
			if(testWhitelists(url,windowURL,type)){
				return true;
			}else{
				return false;
			}
		}
	}else if(url.indexOf("sifr.js") != (-1) && nodeName === "SCRIPT" && safari.extension.settings.sIFR === "blockJS"){
		return false;
	}else if(url.toLowerCase().indexOf("youtube.com/embed/") != -1 && nodeName === "IFRAME"){
		return false;
	}else{
		return true;
	}
}

function sortYouTubeFormats(a,b){	
	var formatOrder = [];
	formatOrder[0] = 0;
	formatOrder[5] = 3;
	formatOrder[6] = 5;
	formatOrder[34] = 7;
	formatOrder[35] = 9;
	formatOrder[18] = 10;
	formatOrder[43] = 11;
	formatOrder[45] = 12;
	formatOrder[22] = 13;
	formatOrder[37] = 15;
	formatOrder[38] = 17;
	if(a.fmt == b.fmt){
		return 0;
	}
	if(formatOrder[a.fmt] < formatOrder[b.fmt]){
		return -1;
	}
	if(formatOrder[a.fmt] > formatOrder[b.fmt]){
		return 1;
	}
}

function setWhitelistWithType(type,whitelist){
	if(type == "host"){
		safari.extension.settings.host_whitelist = whitelist.join("|");
		return true;
	}else if(type == "site"){
		safari.extension.settings.site_whitelist = whitelist.join("|");
		return true;
	}else{
		return false;
	}
}

function loadHTML5Video(event) {
	if (safari.extension.settings.enableHTML5Video === true && event.message) {
		event.target.page.dispatchMessage("injectHTML5Video", event.message);
	}
}

function loadJibJab(event){
	var video = event.message;
	var request = new XMLHttpRequest();
	if(video.id.indexOf("http") != -1){
		var XMLURL = video.id;
		request.open('GET', XMLURL ,false);
	}else{
		var XMLURL = "http://sendables.jibjab.com/api/templates/show/" + video.id;
		request.open('POST',XMLURL,false);
		request.setRequestHeader("X-Wsse",'UsernameToken Username="JibJab", PasswordDigest="mYZI3OjkWThY9bBdbr9+sqD2bhk=", Nonce="VGh1IEp1biAyNCAxNzozNToxNCBHTVQtMDUwMCAyMDEw", Created="2010-06-24T17:35:14Z"')
	}
	request.send(null);
	var responseXML = new DOMParser().parseFromString(request.responseText,"text/xml");
	var element = responseXML.getElementsByTagName("feature")[0];
	if(element){
		video.src = element.getElementsByTagName("asset")[0].getAttribute("url");
	}else{
		return false;
	}
	var element2 = responseXML.getElementsByTagName("thumbnails")[0];
	if(element2){
		video.posterFrame = element2.getElementsByTagName("asset")[0].getAttribute("url");
	}
	if(video.src.indexOf("flv") == -1){
		event.target.page.dispatchMessage("restoreVideo",video.playerId);
	}else{
		event.target.page.dispatchMessage("injectVideo",video);
	}
}

function loadIGN(event){
	var video = event.message;
	try{
		if(video.id.indexOf("{") == -1){
			var split = video.id.split("|");
			var playlistURL = "http://api.ign.com/tt/global_embed_config.t?object="+split[1]+"&vgroup="+split[0]+"&network="+split[2];
			var req = new XMLHttpRequest();
			req.open('GET', playlistURL,false);
			req.send(null);
			video.posterFrame = video.flashVars.image;
			var responseJSON = JSON.parse(req.responseText);
		}else{
			responseJSON = JSON.parse(video.id);
		}
		if(responseJSON.clip){
			if(responseJSON.clip.url){
				video.src = responseJSON.clip.url;
			}else{
				video.src = responseJSON.playlist[1].url;
				video.posterFrame = responseJSON.playlist[0].url;
			}
			video.autoplay = responseJSON.clip.autoPlay;
			event.target.page.dispatchMessage("injectVideo",video);
		}else{
			event.target.page.dispatchMessage("restoreVideo",video.playerId);
		}
	}catch(err){
		alert(JSON.stringify(err));
		alert(JSON.stringify(responseJSON));
		event.target.page.dispatchMessage("restoreVideo",video.playerId);
	}
}

function loadJW(event){
	var video = event.message;
	try{
		var playlistURL = video.id;
		var req = new XMLHttpRequest();
		req.open('GET', playlistURL,false);
		req.send(null);
		video.posterFrame = video.flashVars.image;
		var responseXML = new DOMParser().parseFromString(req.responseText,"text/xml");
		if(responseXML.getElementsByTagName("location").length > 0){
			video.src = responseXML.getElementsByTagName("location")[0].childNodes[0].nodeValue;
			event.target.page.dispatchMessage("injectVideo",video);
		}else{
			event.target.page.dispatchMessage("restoreVideo",video.playerId);
		}
	}catch(err){
		event.target.page.dispatchMessage("restoreVideo",video.playerId);
	}
}

function loadVeoh(event){
	video = event.message;
	videoID = video.id;
	var request = new XMLHttpRequest();
	var playlistURL = "http://www.veoh.com/rest/video/"+videoID+"/details";
	request.open('GET', playlistURL,false);
	request.send(null);
	var responseXML = new DOMParser().parseFromString(request.responseText,"text/xml");
	element = responseXML.getElementsByTagName("video")[0];
	if(element){
		URL = element.getAttribute("fullPreviewHashPath");
	}else{
		return false;
	}
	video.src = URL;
	video.posterFrame = element.getAttribute("fullPreviewHashPath");
	event.target.page.dispatchMessage("injectVideo",video);
}

function loadVimeo(event){
	video = event.message;
	videoID = video.id;
	var request = new XMLHttpRequest();
	var playlistURL = "http://www.vimeo.com/moogaloop/load/clip:"+videoID+"/";
	request.open('GET', playlistURL,false);
	request.send(null);
	var responseXML = new DOMParser().parseFromString(request.responseText,"text/xml");
	video.src = responseXML.getElementsByTagName("file")[0].childNodes[0].nodeValue;
	video.posterFrame = responseXML.getElementsByTagName("thumbnail")[0].childNodes[0].nodeValue;
	event.target.page.dispatchMessage("injectVideo",video);
}

function loadCollegeHumor(event){
	video = event.message;
	videoID = video.id;
	var request = new XMLHttpRequest();
	var playlistURL = "http://www.collegehumor.com/moogaloop/video:"+videoID;
	request.open('GET', playlistURL,false);
	request.send(null);
	var responseXML = new DOMParser().parseFromString(request.responseText,"text/xml");
	if(responseXML.getElementsByTagName("file").length > 0){
		video.src = responseXML.getElementsByTagName("file")[0].childNodes[0].nodeValue;
		video.posterFrame = responseXML.getElementsByTagName("thumbnail")[0].childNodes[0].nodeValue;
		event.target.page.dispatchMessage("injectVideo",video);
	}else{
		event.target.page.dispatchMessage("restoreVideo",video);
	}
}

function getVideoFromMegavideo(video){
	var str_bin = "";
	//1. Convert hex "un" to binary
	for(var i = 0; i < video.un.length; i++){
		str_bin = str_bin + zeroPad(parseInt(video.un.charAt(i),16).toString(2),4);
	}
	var arr_bin = str_bin.split("");
	//2. Generate and switch XOR keys
	var key = Array();
	var key1 = video.k1;
	var key2 = video.k2;
	for(var x = 0; x < 384; x++){
		key1 = (key1 * 11 + 77213) % 81371;
		key2 = (key2 * 17 + 92717) % 192811;
		key[x] = ( key1 + key2 ) % 128;
	}
	//3. Switch bits positions
	for(var y = 256; y >= 0; y--){
		var temp = arr_bin[key[y]];
		arr_bin[key[y]] = arr_bin[y%128];
		arr_bin[y%128] = temp;
	}
	//4. XOR entire binary string
	for(var z = 0; z < 128; z++){
		arr_bin[z] = arr_bin[z] ^ key[z+256] & 1;
	}
	//5. Convert binary string back to hex
	str_bin = arr_bin.join("");
	var str_hex = "";
	for(var j = 0; j < 32; j++){
		str_hex = str_hex + parseInt(str_bin.substr(j*4,4),2).toString(16);
	}
	return "http://www"+video.s+".megavideo.com/files/"+str_hex+"/video.flv";
}

function zeroPad(num,count){
	var numZeropad = num + '';
	while(numZeropad.length < count) {
		numZeropad = "0" + numZeropad;
	}
return numZeropad;
}

function loadMegaVideo(event){
	video = event.message;
	videoID = video.id;
	if(videoID.length != 8){
		var idReq = new XMLHttpRequest();
		idReq.open("GET","http://combsconnections.tk/cmds.php?cmd=getMegaVideo&id="+videoID,false);
		idReq.send();
		videoID = idReq.responseText;
	}
	var request = new XMLHttpRequest();
	var playlistURL = "http://www.megavideo.com/xml/videolink.php?v="+videoID;
	request.open('GET', playlistURL,false);
	request.send(null);
	var responseXML = new DOMParser().parseFromString(request.responseText,"text/xml");
	var embed = responseXML.getElementsByTagName("ROW")[0];
	if(embed.getAttribute("errortext")){
		event.target.page.dispatchMessage("restoreVideo",video.playerId);
		return;
	}
	video.k1 = embed.getAttribute("k1");
	video.k2 = embed.getAttribute("k2");
	video.un = embed.getAttribute("un");
	video.s = embed.getAttribute("s");
	video.v = videoID;
	video.src = getVideoFromMegavideo(video);
	event.target.page.dispatchMessage("injectVideo",video);
}

function decodeViddler(encodedString){
	alert(encodedString);
}

function loadG4TV(event){
	var video = event.message;
	var videoID = video.id;
	var xhr = new XMLHttpRequest();
	xhr.open("GET","http://www.g4tv.com/xml/BroadbandPlayerService.asmx/GetEmbeddedVideo?strPlaylist=&playLargeVideo=true&excludedVideoKeys=&playlistType=normal&maxPlaylistSize=10&videoKey="+videoID,false);
	xhr.send();
	try{
		video.src = xhr.responseXML.querySelector('Video[Key="'+videoID+'"]').getElementsByTagName("FilePath").firstChild.nodeValue;
		video.posterFrame = xhr.responseXML.querySelector('Video[Key="'+videoID+'"]').getElementsByTagName("LargeImage").firstChild.nodeValue;
		event.target.page.dispatchMessage("injectVideo",video);
	}catch(e){
		event.target.page.dispatchMessage("restoreVideo",video.playerId);
	}
}

function loadViddlerVideo(event){
	var video = event.message;
	var xhr = new XMLHttpRequest();
	xhr.open("POST","http://www.viddler.com/amfgateway.action",false);
	xhr.overrideMimeType("application/x-amf");
	// Some special AMF stuff I'll never understand completely
	xhr.send(unescape("%00%00%00%00%00%01%00%1b")+"viddlerGateway.getVideoInfo"+unescape("%00%02%2f%31%00%00%00%12%0a%00%00%00%03%02%00%08")+video.id+unescape("%05%05"));
	video.posterFrame = "http://cdn.static.viddler.com/embedlogo/"+escape(xhr.responseText).between("logo%02%00%15","%00%0A");
	video.src = decodeViddler(escape(xhr.responseText).between("path%02%00%uFFFD","%00%04"));
	event.target.page.dispatchMessage("injectVideo",video);
	return;
}

function getYouTubeSrcFromPage(pageSrc,oldSrc){
	if(pageSrc.indexOf(unescape("formatListFromMap%28%0A")) == -1){
		return oldSrc;
	}
	if(!oldSrc){
		oldSrc = [];
	}
	var map;
	map = pageSrc.between(unescape("formatListFromMap%28%0A"),");");
	if(!map){
		return oldSrc;
	}
	var jsonInfo = JSON.parse(map.trim());
	var str = "";
	for(var i = 0; i < jsonInfo.length; i++){
		var fmt = jsonInfo[i];
		str += fmt.itag+"|"+fmt.url+",";
	}
	return getYouTubeSrc(str.slice(0, -1),oldSrc,pageSrc.between('<meta name="title" content="','"'),pageSrc.between('"fmt_map": "','", "').replace(/\\/g,""));
}

function getYouTubeSrc(videoFormats,usableFormats,title,fmtMap){

	if(!usableFormats){
		usableFormats = [];
	}
	
	if(!videoFormats || typeof videoFormats !== "string"){
		return usableFormats;
	}
	var formats = videoFormats.split(',');
	
	for(var i = 0; i<formats.length; i++){
		var meta = getQueryString(formats[i]);
		var fmt = parseInt(meta.itag,10);
		if((fmt == 18 || fmt == 22 || fmt == 37 || fmt == 38) ||
			(supportsFLV && safari.extension.settings.allowFLV === true && (fmt == 35 || fmt == 34 || fmt == 0  || fmt == 5  || fmt == 6)) ||
			(supportsWebM && (fmt == 43 || fmt == 45))){
			usableFormats.push({fmt: fmt, url: meta.url, quality: meta.quality, fallback_host: meta.fallback_host, type: meta.type, });
		}
	}
	
	var formatTypes = {
		0: {name: "240p", type: FLV, HD: false, size: {height: 240, width: 400}},
		5: {name: "240p", type: FLV, HD: false, size: {height: 240, width: 400}},
		6: {name: "360p", type: FLV, HD: false, size: {height: 360, width: 480}},
		18: {name: "360p", type: MP4, HD: false, size: {height: 360, width: 480}},
		34: {name: "360p", type: FLV, HD: false, size: {height: 360, width: 640}},
		35: {name: "480p", type: FLV, HD: false, size: {height: 480, width: 854}},
		22: {name: "720p", type: MP4, HD: true, size: {height: 720, width: 1280}},
		37: {name: "1080p", type: MP4, HD: true, size: {height: 1080, width: 1920}},
		38: {name: "Original", type: MP4, HD: true, size: {height: 3072, width: 4096}},
		43: {name: "480p", type: WEBM, HD: false, size: {height: 480, width: 854}},
		45: {name: "720p", type: WEBM, HD: true, size: {height: 720, width: 1280}}
	};
	
	if(!fmtMap.contains("x")){
		return usableFormats;
	}
	var fmt_map = fmtMap.split(",");
	for(i = 0; i < fmt_map.length; i++){
		var fmt = fmt_map[i].split("/");
		var size = fmt[1].split("x");
	}
	
	for(var x = 0; x < usableFormats.length; x++){
		usableFormats[x].type = formatTypes[usableFormats[x].fmt];
	}
	
	usableFormats.sort(sortYouTubeFormats);
	
	var currentFmt = usableFormats[0];
	for(var y = 1; y < usableFormats.length; y++){
		if(title){
			if(!usableFormats[y].url.contains("title=")){
				usableFormats[y].url += ("&title="+encodeURIComponent(title+" ("+usableFormats[y].type.name+" "+usableFormats[y].type.type+")"));
			}
		}
		if(usableFormats[y].fmt == currentFmt.fmt){
			usableFormats.remove(y);
			y--;
		}else{
			currentFmt = usableFormats[y];
		}
		
	}
	
	return usableFormats.reverse();
}

function loadNextYouTubeVideo(event){
	var video = event.message;
	
	video.src = [];
	
	video = getYouTubeInfo(video,event);
	
	if(video.src.length == 0){
		event.target.page.dispatchMessage("finishVideo", video.playerId);
	}else{
		event.target.page.dispatchMessage("loadNewVideo", video);
	}
}

function loadYoutubeVideo(event) {
	var video = event.message;
	
	video.src = [];
	console.log(video.flashVars.url_encoded_fmt_stream_map)
	
	if(video.flashVars.url_encoded_fmt_stream_map){
		video.src = getYouTubeSrc(video.flashVars.url_encoded_fmt_stream_map,video.src,video.flashVars.title,video.flashVars.fmt_list);
		video.duration = video.flashVars.length_seconds;
	}
	
	video2 = getYouTubeInfo(video,event);
	
	if(!video2 || !video2.src || video2.src.length == 0){
		event.target.page.dispatchMessage("restoreVideo", video.playerId);
	}else{
		event.target.page.dispatchMessage("injectVideo", video2);
	}
}

function getYouTubeInfo(video,event){

	if(safari.extension.settings.show_annotations === true){
		var ann_req = new XMLHttpRequest();
		
		ann_req.open("GET", "http://www.youtube.com/annotations/read2?video_id=" + video.id, false);
		ann_req.send(null);
		
		var responseXML = ann_req.responseXML;
		if(responseXML.documentElement.getAttribute("status") != "404"){
			video.hasAnnotations = true;
			var parsedAnnotations = parseAnnotations(responseXML);
			video.annotations = parsedAnnotations;
		}else{
			video.hasAnnotations = false;
		}
	}else{
		video.hasAnnotations = false;
	}
	
	var req = new XMLHttpRequest();

	req.open('GET', 'http://www.youtube.com/get_video_info?ypc_preview=1&el=detailpage&asv=3&hl=en_US&video_id=' + video.id, false);
	req.send(null);
	var queryString = getQueryString(req.responseText);
	var errno;
	if(errno = queryString.errorcode){
		if(errno == 100){
			return;
		}
	}
	if(queryString.url_encoded_fmt_stream_map){
		video.duration = queryString.length_seconds;
		video.src = getYouTubeSrc(queryString.url_encoded_fmt_stream_map,video.src,queryString.title,queryString.fmt_list);
	}
	
	if(video.src.length == 0 || supportsWebM){
			var webmReq = new XMLHttpRequest();
			webmReq.open("GET","http://www.youtube.com/watch?v="+video.id+"&html5=1",false);
			webmReq.send();
			video.src = getYouTubeSrcFromPage(webmReq.responseText,video.src);
	}
	return video;
}

function handleMessage(event) {
	try{
	switch (event.name) {
	case "loadVideo":
		loadYoutubeVideo(event);
		break;
	
	case "loadNextYouTubeVideo":
		loadNextYouTubeVideo(event);
		break;
		
	case "loadViddlerVideo":
		loadViddlerVideo(event);
		break;

	case "loadHTML5Video":
		loadHTML5Video(event);
		break;
		
	case "loadVeoh":
		loadVeoh(event);
		break;
		
	case "loadVimeo":
		loadVimeo(event);
		break;
		
	case "loadCollegeHumor":
		loadCollegeHumor(event);
		break;
		
	case "loadMegaVideo":
		loadMegaVideo(event);
		break;
		
	case "loadIGN":
		loadIGN(event);
		break;
	
	case "loadJibJab":
		loadJibJab(event);
		break;
		
	case "loadJW":
		loadJW(event);
		break;

	case "canLoad":
		var data = event.message;
		event.message = allowContentToLoad(data.url, data.nodeName, data.width, data.height, data.elid, data.className, data.windowURL, data.type);
		break;
	}
	}catch(err){
		alert(JSON.stringify(err));
	}
}

safari.application.addEventListener("message", handleMessage, false);

function handleCommand(event){
	if(event.command === "downloadVideo"){
		if(event.userInfo.className.contains("video-format-item")){
			downloadURL(event.userInfo.fmt.url);
		}else{
			downloadURL(event.userInfo.src);
		}
	}
	if(event.command === "quicktime"){
		if(event.userInfo.className.contains("video-format-item")){
			viewInQuickTimePlayer(event.userInfo.fmt.url);
		}else{
			viewInQuickTimePlayer(event.userInfo.src);
		}
	}
	if(event.command === "airflick"){
		if(event.userInfo.className.contains("video-format-item")){
			var thisTab = safari.application.activeBrowserWindow.activeTab;
			var newTab = safari.application.activeBrowserWindow.openTab();
			newTab.url = event.userInfo.src = "airflick://play-media?MediaLocation="+encodeURI(event.userInfo.fmt.url);
			newTab.close();
			thisTab.activate();
		}else{
			var thisTab = safari.application.activeBrowserWindow.activeTab;
			var newTab = safari.application.activeBrowserWindow.openTab();
			newTab.url = event.userInfo.src = "airflick://play-media?MediaLocation="+encodeURI(event.userInfo.src);
			newTab.close();
			thisTab.activate();
		}
	}
	if(event.command === "viewOnSite"){
		var tab = safari.application.activeBrowserWindow.openTab();
		tab.url = event.userInfo.targetURL;
		tab.activate();
	}
	if(event.command === "restoreVideo"){
		safari.application.activeBrowserWindow.activeTab.page.dispatchMessage("restoreVideo",event.userInfo.id);
	}
	if(event.command === "unblockAll"){
		safari.application.activeBrowserWindow.activeTab.page.dispatchMessage("unblockAll","");
	}
}

safari.application.addEventListener("command", handleCommand, false);

function handleValidate(event){
	if(event.command === "downloadVideo" || event.command === "airflick" || event.command === "quicktime"){
		if(event.userInfo.nodeName === "VIDEO" || event.userInfo.nodeName === "AUDIO" || event.userInfo.className.contains("video-format-item")){
			event.target.disabled = false;
		}else{
			event.target.disabled = true;
		}
	}
	if(event.command === "viewOnSite"){
		if(event.userInfo.targetName && event.userInfo.targetURL){
			event.target.disabled = false;
			event.target.title = "View on " + event.userInfo.targetName;
		}else{
			event.target.disabled = true;
		}
	}
	if(event.command === "restoreVideo"){
		if(event.userInfo.nodeName === "VIDEO" && event.userInfo.className.indexOf("html5-video-player-tag") != -1){
			event.target.disabled = false;
		}else{
			event.target.disabled = true;
		}
	}
}
safari.application.addEventListener("validate", handleValidate, false);
</script>
</head>
</html>